<?php


namespace App\Services;


class Base
{
    //AES加密解密 
    public function encrypt($str,$key = '')
    {
        $key = $this->getAesKey($key);
        return base64_encode(openssl_encrypt($str,"AES-128-ECB",$key,OPENSSL_RAW_DATA));
    }

    public function decrypt($str,$key = '')
    {
        $key = $this->getAesKey($key);
        return openssl_decrypt(base64_decode($str),"AES-128-ECB",$key, OPENSSL_RAW_DATA);
    }

    private function getAesKey($key)
    {
        return $key==''?env("API_SECRET_KEY"):$key;
    }

    //签名使用随机数
    public function random($length = 16)
    {
        $string = '';

        while (($len = strlen($string)) < $length) {
            $size = $length - $len;

            $bytes = function_exists('random_bytes')
                ? random_bytes($size) : mt_rand();

            $encoded = str_replace(['/', '+', '='], '', base64_encode($bytes));

            $string .= substr($encoded, 0, $size);
        }

        return $string;
    }

}